import React, { Component } from "react";
import storeutil from "../../util/storeutil";
import { withRouter } from "react-router-dom";
import menuList from "../../config/menuConfig";
import { formdateDate } from "../../util/datatutil";

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTime: formdateDate(Date.now()),
    };
  }
  getTime = () => {
    this.intervalId = setInterval(() => {
      const currentTime = formdateDate(Date.now());
      this.setState({ currentTime });
    }, 1000);
  };
  getTitle = () => {
    const path = this.props.location.pathname;
    let title;
    menuList.forEach((item) => {
      if (item.key == path) {
        title = item.title;
      } else if (item.children) {
        const cItem = item.children.find(
          (cItem) => path.indexOf(cItem.key) == 0
        );
        if (cItem) {
          title = cItem.title;
        }
      }
    });
    return title;
  };
  logout = () => {
    Modal.confirm({
      content: "确定退出?",
      onOk: () => {
        console.log("OK", this);
        storeutil.removeUser();
        this.props.history.replace("/login");
      },
    });
  };
  componentDidMount() {
    this.getTime();
  }
  componentWillUnmount() {
    clearInterval(this.intervalId);
  }
  render() {
    const { currentTime } = this.state;
    const user = storeutil.getUser();
    const { username } = user;
    const title = this.getTitle();
    return (
      <div className="Header">
        <span>欢迎{username}</span>
        <span>当前时间:{currentTime}</span>
        <span>当前位置:{title}</span>
        <button type="primary" onClick={this.logout}>
          退出
        </button>
      </div>
    );
  }
}

export default withRouter(Header);
